<template>
  <div class="ma-notice-management">
    <div class="header-section">
      <h2 class="page-title">通知管理</h2>
      <div class="action-buttons">
        <button class="publish-button" @click="showPublishModal = true">
          发布管理员通知
        </button>
      </div>
    </div>

    <div class="management-tabs">
      <button
        :class="{ active: currentTab === 'review' }"
        @click="currentTab = 'review'; fetchReviewNotices()"
        class="tab-button"
      >
        审核主办方通知
      </button>
      <button
        :class="{ active: currentTab === 'published' }"
        @click="currentTab = 'published'"
        class="tab-button"
      >
        我发布的通知
      </button>
    </div>

    <!-- 审核主办方通知 -->
    <div v-if="currentTab === 'review'" class="tab-content">
      <div class="filter-section">
        <div class="filter-buttons">
          <button
            :class="{ active: reviewFilter === 'pending' }"
            @click="reviewFilter = 'pending'"
          >
            待审核
          </button>
          <button
            :class="{ active: reviewFilter === 'approved' }"
            @click="reviewFilter = 'approved'"
          >
            已通过
          </button>
        </div>
      </div>

      <div class="notice-list">
        <div v-if="reviewLoading" class="loading">加载中...</div>
        <div v-else-if="filteredReviewNotices.length === 0" class="no-notices">
          {{ getReviewEmptyMessage() }}
        </div>
        <div v-else class="notice-items">
          <div v-for="notice in filteredReviewNotices" :key="notice.id" class="notice-item">
            <div class="notice-header">
              <h3>{{ notice.title }}</h3>
              <span class="sender-info">来自: {{ getSenderInfo(notice) }}</span>
            </div>
            <div class="notice-content">
              {{ notice.content }}
            </div>
            <div class="notice-meta">
              <span class="create-time">{{ formatDate(notice.createTime) }}</span>
              <span class="receiver-type">{{ getReceiverType(notice.receiverType) }}可见</span>
              <span class="status" :class="getStatusClass(notice.isUsing)">
                {{ getAuditStatus(notice.isUsing) }}
              </span>
            </div>
            <div v-if="!notice.isUsing && reviewFilter === 'pending'" class="review-actions">
              <button class="approve-btn" @click="handleApprove(notice.id)">
                通过审核
              </button>
              <button class="reject-btn" @click="handleReject(notice.id)">
                拒绝审核
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 我发布的通知 -->
    <div v-else-if="currentTab === 'published'" class="tab-content">
      <MAShowNotice />
    </div>

    <!-- 发布通知模态框 -->
    <div v-if="showPublishModal" class="modal-overlay">
      <div class="modal-content">
        <div class="modal-header">
          <h3>发布管理员通知</h3>
          <button class="close-button" @click="closePublishModal">×</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label for="noticeTitle">通知标题：</label>
            <input
              type="text"
              id="noticeTitle"
              v-model="newNotice.title"
              class="form-input"
              placeholder="请输入通知标题"
            >
          </div>
          <div class="form-group">
            <label for="noticeContent">通知内容：</label>
            <textarea
              id="noticeContent"
              v-model="newNotice.content"
              class="form-textarea"
              placeholder="请输入通知内容"
              rows="6"
            ></textarea>
          </div>
          <div class="form-group">
            <label for="receiverType">接收对象：</label>
            <select id="receiverType" v-model="newNotice.receiverType" class="form-select">
              <option value="1">所有人</option>
              <option value="2">管理员</option>
              <option value="3">主办方</option>
              <option value="4">用户</option>
              <option value="5">非管理员</option>
              <option value="6">非主办方</option>
              <option value="7">非用户</option>
            </select>
          </div>
        </div>
        <div class="modal-actions">
          <button class="submit-button" @click="publishNotice" :disabled="!isFormValid">
            发布通知
          </button>
          <button class="cancel-button" @click="closePublishModal">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import MAShowNotice from './MA_show_notice.vue'

interface Notice {
  id: number
  senderType: number
  senderId: number
  receiverType: number
  receiverOneType: number | null
  receiverId: number | null
  title: string
  content: string
  createTime: string
  isUsing: boolean
  senderName?: string
}

const currentTab = ref<'review' | 'published'>('review')
const reviewFilter = ref<'pending' | 'approved'>('pending')
const reviewLoading = ref(false)
const showPublishModal = ref(false)
const reviewNotices = ref<Notice[]>([])

const newNotice = ref({
  title: '',
  content: '',
  receiverType: '1'
})

// 获取待审核的主办方通知
const fetchReviewNotices = async () => {
  reviewLoading.value = true
  try {
    const token = localStorage.getItem('token')

    if (!token) {
      alert('未找到有效的身份凭证，请重新登录')
      return
    }

    const response = await fetch('http://localhost:8080/notice/pending', {
      method: 'GET',
      headers: {
        'token': token
      }
    })

    if (response.ok) {
      const result = await response.json()

      if (result.success) {
        reviewNotices.value = result.notices || []
        console.log('获取到的通知:', reviewNotices.value)
      } else {
        alert('获取待审核通知失败: ' + (result.message || '未知错误'))
      }
    } else {
      alert('网络请求失败，状态码: ' + response.status)
    }
  } catch (error) {
    console.error('获取待审核通知时出错:', error)
    alert('获取待审核通知时发生错误: ' + error)
  } finally {
    reviewLoading.value = false
  }
}

// 筛选待审核通知
const filteredReviewNotices = computed(() => {
  if (reviewFilter.value === 'pending') {
    return reviewNotices.value.filter(notice => !notice.isUsing)
  } else {
    return reviewNotices.value.filter(notice => notice.isUsing)
  }
})

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 获取发送者信息
const getSenderInfo = (notice: Notice) => {
  return notice.senderType === 1 ? '主办方' : '未知'
}

// 获取接收者类型
const getReceiverType = (type: number) => {
  switch (type) {
    case 0: return '单独发送'
    case 1: return '所有人'
    case 2: return '管理员'
    case 3: return '主办方'
    case 4: return '用户'
    case 5: return '非管理员'
    case 6: return '非主办方'
    case 7: return '非用户'
    default: return '未知'
  }
}

// 获取审核状态
const getAuditStatus = (status: boolean) => {
  return status ? '已通过' : '待审核'
}

// 获取状态样式类
const getStatusClass = (status: boolean) => {
  return status ? 'status-approved' : 'status-pending'
}

// 获取空状态消息
const getReviewEmptyMessage = () => {
  switch (reviewFilter.value) {
    case 'pending': return '暂无待审核通知'
    case 'approved': return '暂无已通过通知'
    default: return '暂无通知'
  }
}

// 处理通过审核
const handleApprove = async (noticeId: number) => {
  try {
    const token = localStorage.getItem('token')

    const response = await fetch(`http://localhost:8080/notice/review?id=${noticeId}&isUsing=true`, {
      method: 'PUT',
      headers: {
        'token': token || ''
      }
    })

    if (response.ok) {
      const result = await response.json()

      if (result.success) {
        alert('审核通过')
        // 立即更新本地数据，而不是重新请求
        const noticeIndex = reviewNotices.value.findIndex(n => n.id === noticeId)
        if (noticeIndex !== -1) {
          reviewNotices.value[noticeIndex].isUsing = true
        }
        // 如果当前在"已通过"标签页，自动刷新数据确保显示最新
        if (reviewFilter.value === 'approved') {
          fetchReviewNotices()
        }
      } else {
        alert('审核失败: ' + (result.message || '未知错误'))
      }
    } else {
      alert('网络请求失败，状态码: ' + response.status)
    }
  } catch (error) {
    console.error('审核通知时出错:', error)
    alert('审核通知时发生错误: ' + error)
  }
}

// 处理拒绝审核
const handleReject = async (noticeId: number) => {
  try {
    const token = localStorage.getItem('token')
    const response = await fetch(`http://localhost:8080/notice/review?id=${noticeId}&isUsing=false`, {
      method: 'PUT',
      headers: {
        'token': token || ''
      }
    })

    if (response.ok) {
      const result = await response.json()
      if (result.success) {
        alert('已拒绝')
        // 从列表中移除被拒绝的通知
        reviewNotices.value = reviewNotices.value.filter(n => n.id !== noticeId)
      } else {
        alert('操作失败: ' + (result.message || '未知错误'))
      }
    } else {
      alert('网络请求失败')
    }
  } catch (error) {
    console.error('拒绝通知时出错:', error)
    alert('拒绝通知时发生错误')
  }
}

// 发布通知
const publishNotice = async () => {
  try {
    const token = localStorage.getItem('token')

    const response = await fetch('http://localhost:8080/notice/publish', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'token': token || ''
      },
      body: JSON.stringify({
        title: newNotice.value.title,
        content: newNotice.value.content,
        receiverType: parseInt(newNotice.value.receiverType)
      })
    })

    if (response.ok) {
      const result = await response.json()

      if (result.success) {
        alert('通知发布成功')
        closePublishModal()
        // 切换到已发布通知标签页
        currentTab.value = 'published'
      } else {
        alert('发布失败: ' + (result.message || '未知错误'))
      }
    } else {
      alert('网络请求失败，状态码: ' + response.status)
    }
  } catch (error) {
    console.error('发布通知时出错:', error)
    alert('发布通知时发生错误: ' + error)
  }
}

// 表单验证
const isFormValid = computed(() => {
  return newNotice.value.title.trim() !== '' &&
         newNotice.value.content.trim() !== ''
})

const closePublishModal = () => {
  showPublishModal.value = false
  // 重置表单
  newNotice.value = {
    title: '',
    content: '',
    receiverType: '1'
  }
}

onMounted(() => {
  fetchReviewNotices()
})
</script>


<style scoped>
.ma-notice-management {
  width: 100%;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 32px;
  color: #2E7D32;
  text-shadow: 0 0 8px rgba(56, 142, 60, 0.5);
  font-family: '微软雅黑', sans-serif;
  font-weight: bold;
  margin: 0;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.publish-button {
  padding: 12px 24px;
  background: linear-gradient(to right, #66BB6A, #43A047);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  font-family: '微软雅黑 Light', sans-serif;
}

.publish-button:hover {
  background: linear-gradient(to right, #558B2F, #388E3C);
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.3);
}

.management-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  border-bottom: 1px solid #ddd;
}

.tab-button {
  padding: 12px 24px;
  background: none;
  border: none;
  border-bottom: 3px solid transparent;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #666;
}

.tab-button.active {
  color: #2E7D32;
  border-bottom-color: #2E7D32;
}

.tab-button:hover {
  color: #2E7D32;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-buttons {
  display: flex;
  gap: 10px;
}

.filter-buttons button {
  padding: 8px 16px;
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.filter-buttons button.active,
.filter-buttons button:hover {
  background: linear-gradient(to right, #66BB6A, #43A047);
  color: white;
  border-color: #43A047;
}

.notice-list {
  background: none;
  border: none;
  border-radius: 0;
  padding: 0;
  min-height: 300px;
  box-shadow: none;
}

.loading, .no-notices {
  text-align: center;
  padding: 20px;
  color: #666;
  font-size: 18px;
}

.notice-items {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.notice-item {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  background-color: #f9f9f9;
}

.notice-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.notice-header h3 {
  margin: 0;
  color: #388E3C;
  font-size: 18px;
  font-weight: bold;
}

.sender-info {
  font-size: 14px;
  color: #666;
}

.notice-content {
  margin-bottom: 10px;
  line-height: 1.5;
  font-size: 16px;
}

.notice-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #666;
}

.create-time, .receiver-type {
  font-size: 14px;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.status-pending {
  background-color: #FFF3CD;
  color: #856404;
}

.status-approved {
  background-color: #D1ECF1;
  color: #0C5460;
}

.review-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
  justify-content: flex-end;
}

.approve-btn {
  padding: 8px 16px;
  background: linear-gradient(to right, #66BB6A, #43A047);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.approve-btn:hover {
  background: linear-gradient(to right, #558B2F, #388E3C);
  transform: translateY(-1px);
}

.reject-btn {
  padding: 8px 16px;
  background: linear-gradient(to right, #EF5350, #E53935);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.reject-btn:hover {
  background: linear-gradient(to right, #E53935, #C62828);
  transform: translateY(-1px);
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #ddd;
}

.modal-header h3 {
  margin: 0;
  color: #2E7D32;
}

.close-button {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.close-button:hover {
  color: #333;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
  color: #2E7D32;
}

.form-input,
.form-textarea,
.form-select {
  width: 100%;
  padding: 10px;
  border: 1px solid #A5D6A7;
  border-radius: 4px;
  font-size: 16px;
  box-sizing: border-box;
}

.form-textarea {
  resize: vertical;
  min-height: 120px;
}

.modal-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
  padding: 20px;
  border-top: 1px solid #ddd;
}

.submit-button {
  padding: 12px 25px;
  background: linear-gradient(to right, #4CAF50, #45a049);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.submit-button:disabled {
  background: #ccc;
  cursor: not-allowed;
  transform: none;
}

.submit-button:not(:disabled):hover {
  background: linear-gradient(to right, #45a049, #4CAF50);
  transform: translateY(-2px);
}

.cancel-button {
  padding: 12px 25px;
  background: #f5f5f5;
  color: #666;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cancel-button:hover {
  background: #e0e0e0;
}
</style>
